< previous page page_171 next page >

Page 171
What's Different About Constants
Using variables is just one way of storing information in the memory of a computer. Another way is to use constants. Constants in a program are treated a special way. After you define them (or they are defined for you by Visual Basic), you cannot modify them later in the program. If you try, Visual Basic generates an error when you run your program. It may help you to think of a constant as a variable whose value cannot change.
How to Use Constants
Constants are most often used to replace a value that is hard to remember or to type, such as the color value for the Windows title bar. Remembering the constant vbActiveTitleBar is easier than remembering the value -2147483646. You can also use a constant to avoid typing long strings if they are used in a number of places. For example, you can set a constant such as FileErrMsg containing the string "The requested file was not found."
Constants are also used frequently for conversion factors, such as 12 inches per foot or 3.3 feet per meter. The following code example shows how constants and variables are used:
Const MetersToFeet = 3.3
nDistMeters = InputBox("Enter a distance in meters")
nDistFeet = nDistMeters * MetersToFeet
MsgBox "The distance in feet is: " &  CStr(nDistFeet)
Another common use for constants is to minimize changes to your code for reasons such as changing your program's name, version number, and so forth. You can define constants at the beginning of your program and use the predefined constants throughout the program. Then, when a version number changes, all you need to do is change the declaration of the constant. The following example illustrates this technique:
Public Const ProgTitle = "My Application Name"
Public Const ProgVersion = "3.1"
Note the use of the Public keyword, which makes these constants available throughout the application (assuming that their declaration is in a module).
Constants That Visual Basic Supplies
Visual Basic supplies a number of built-in constants for various activities. They are known as intrinsic constants. Color-definition constants, data-access constants, keycode constants, and shape constants, among many others, are available. Especially useful are constants correlating to a command's parameter information, such as the vbExclamation constant used for a MessageBox statement in previous chapters.
The constants that you need for most functions are described in the help system's topic for the function. If you want to know the value of a particular constant, you can use the Object Browser (see Figure 8.3). Access the Object Browser by clicking its icon in the Visual Basic toolbar, by selecting View, Object Browser from the menu system, or simply by pressingF2. You can use the list to find the constant that you want. When you select it, its value and function are displayed in the text area at the bottom of the dialog box.

 
< previous page page_171 next page >